package com.mumulx.check.receiver;

import com.mumulx.check.redis.entity.CheckPartContants;
import com.mumulx.check.redis.entity.PartTestBoxed;
import com.mumulx.check.redis.RedisUtil;
import com.mumulx.check.service.CheckPartService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import nxopen.NXException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/*
 *  Created by IntelliJ IDEA.
 *  User: 木木
 *  Date: 2020/11/3
 *  Time: 23:14
 */
@Component
@Slf4j
public class CheckPartReceiver {


    @Resource
    CheckPartService checkPartService;
    @Resource
    RedisUtil redisUtil;
    @RabbitListener(queues = CheckPartContants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) {
        PartTestBoxed partTestBoxed=(PartTestBoxed)message.getPayload();
        MessageHeaders headers = message.getHeaders();
        Long tag= (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String)headers.get("spring_returned_message_correlation");
        //RedisUtil
        //redis中包含该key，说明该消息已经被消费了
        try {
            if(redisUtil.exists(msgId)){
                log.info("消息已经被消费了----"+msgId);
                channel.basicAck(tag, false);
                return;
            }
            //执行测试任务
            checkPartService.checkpart(partTestBoxed);
            //PartTestBoxed
            log.info("收到消息了---消息任务已经完成----"+partTestBoxed.toString());
            redisUtil.set("msgId", msgId, 10, TimeUnit.HOURS);
            channel.basicAck(tag, false);
        } catch (IOException | NXException e) {
            //当业务处理异常时 消息处理办法
            // false ：是否批处理   true：是否放回消息队列中
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }


    }





    }
